const appInstance = getApp()
var globalData = appInstance.globalData
const common = require('../../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    diet_bg: '/images/sport/sport_bg.jpg',  //饮食记录背景图片
    upload_img: '/images/diet/upload_button.png',
    // upload_imgContent: '/images/diet/upload_button.png',
    notice: '记录自己的运动记录，便于系统为你提出更好的建议，赶快行动吧!',
    username: '用户',
    specific_time: '具体时间',
    time_slot: '时间段',
    food_name: '运动名称',
    strength: '强度',    
    upload_notice: '点击左侧上传图片',
    selectArray: [
      {
        "id": "10",
        "text": "上午"
      }, {
        "id": "21",
        "text": "下午"
      },
      {
        "id": "21",
        "text": "晚上"
      },
    ],
    validateNotice: '',
    isHidden: true, // 是否隐藏验证提示，false：不隐藏
    username_value: '', // 系统提供的用户名值
    specific_value: '', // 系统提供的具体时间值
    UploadImageURL: '', // 要上传图片的后台地址
    requestURL: 'http://localhost:8081/keepfit/addSport',// 请求地址
    nowText: '请选择',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // 这里需要对全局数据中的 ifChoose和 selectItem进行清空，以获取最新的值
    globalData.ifChoose = false
    globalData.selectItem = null
    // 获取具体时间和用户名
    that.setData({
      username_value: that.getCurrentUsername(),
      specific_value: that.getSubmitTime()
    })
  },
  // 处理下拉菜单
  HandleDropMenu(e) {
    console.log(globalData.ifChoose)
    console.log(globalData.selectItem)
  },
  // 表单提交
  HandleForm(e) {
    var that = this
    console.log(e)
    var endValidateResult = false  // 最终校验结果
    var sport_name = e.detail.value.sport_name    
    var strength = e.detail.value.strength
    
    // 用于校验部分格式
    var parms = {
      sport_name: sport_name,      
      strength: strength,
      time_slot: globalData.selectItem,
    }
    console.log("globalData.selectItem="+globalData.selectItem)
    var validateResult=that.validatePattern(parms)
   
    // 格式校验正确
    if (validateResult) {
      // 全部表单的参数
      var AllParms = {
        username: that.data.username_value,
        specific_time: that.data.specific_value,  // 具体时间
        sport_name: sport_name,        
        strength:strength,        
        time_slot: globalData.selectItem,
        img_url: that.data.upload_img,  // 上传的食物图片地址
      }
      // 调用后台接口对数据进行上传
      
      common.addDiet(AllParms, that.data.requestURL)
        .then(res => {
          if (res == 'success') {
            wx.showToast({
              title: '上传成功！',
              icon: 'success',
            })
            that.setData({
              UploadImageURL: '',
              upload_img:'/images/diet/upload_button.png',
            })

          } else {
            wx.showToast({
              title: '上传失败！',
              icon: 'fail',
            })
          }
        })
      that.setData({
        isHidden: true
      })
    } else {
      wx.showToast({
        title: '上传失败！',
        icon: 'error',
      })
      that.setData({
        isHidden: false
      })
      console.log("isHidden=" + that.data.isHidden)
    }

  },
  // 对只包含中文、英文、数字的格式进行校验，首字母不能是数字
  validatePattern(params){
    var validate_timeSlot=false  // 对时间段的校验结果
    var that=this
    var sport_name=params.sport_name
    var strength=params.strength

    var upload_img='/images/diet/upload_button.png'

    var parm={
      sport_name : sport_name,
      strength : strength
    }
    // 时间段
    var time_slot=params.time_slot
    console.log("time_slot="+time_slot)
    if(time_slot=='' || time_slot=='请选择' || time_slot==null){
      validate_timeSlot=false
    }else{
      validate_timeSlot=true
    }
    //校验结果
    var validateResult=false

    var patt_head=/^[0-9]/  //首字母不能是数字
    var patt_contain=/([A-z]|[0-9])/g   // g:全局匹配   
    // 表单输入为空
    if(sport_name==''){
       console.log("sport_name等于null")
    }
    if(strength==''){
      console.log("strength等于null")
    }

    if(that.data.upload_img == upload_img){
      console.log('图片上传为null')
    }

    console.log(sport_name+" "+strength+" "+validate_timeSlot+" "+that.data.upload_img)
    if(sport_name===null || sport_name==='' || strength===null || strength==='' || validate_timeSlot==false || that.data.upload_img == upload_img  ){
      that.setData({
        validateNotice:'表单输入不能为空'
      })
      return validateResult
    }else{  //表单输入不为空
      // 对格式进行校验
      // 1.校验长度
      if(sport_name.length<2 || strength<2 || sport_name.length>12 || strength>12){
        that.setData({
          validateNotice:'字段输入至少是2个至多为12个字符'
        })
        return validateResult
      }else{  //长度合法
        // 校验首字母不为数字
        if(patt_head.test(sport_name) || patt_head.test(strength)){
          that.setData({
            validateNotice:'第一个字符不能是数字'
          })
          return validateResult
        }else{
          // 如果输入的是字母、数字、中文的话
          if( that.isSatisfyPatt( parm ) ){
            validateResult=true
          }else{
            that.setData({
              validateNotice:'输入只能是字母、数字、中文'
            })
            return validateResult
          }
        }
      }
    }
    return validateResult
  },
  // 判断输入文本中是否含有中文
  isChinese(temp) {
    if (escape(temp).indexOf("%u") < 0) {
      return false
    } else {
      return true
    }


  },
  // 校验字符是否全是中文
  isALLChinese(attr){
    var result=true
    var i=0
    for(i=0;i<attr.length;i++){
      if(!this.isChinese(attr[i])){
        result=false
        return result
      }
    }
    return result
  },
  // 判断格式是否为字母、数字、中文
  isSatisfyPatt(parm){
    var that=this
    var patt_head=/^[0-9]/  //首字母不能是数字
    var patt_contain=/([A-z]|[0-9])/g   // g:全局匹配       
    
    var validateResult=true  //校验结果
    var sport_name=parm.sport_name
    var strength=parm.strength
    // 对于运动名称
    // 对于强度
    for(var i=0;i<strength.length;i++){
      if( !( patt_contain.test(strength[i]) || that.isChinese(strength[i]) ) ){
        validateResult=false
        return validateResult
      }else continue
    }
       return validateResult
  },
  // 判断用户是否全部已选
  JudgeisAllSelected(e) {
    var result = false
    var parm = e.detail.value
    //  如果下拉菜单选中了的话
    if (globalData.ifChoose) {
      for (var index in parm) {
        if (parm[index] != null && parm[index] != '') {
          result = true
        } else {
          result = false
          break
        }
      }
    } else {
      result = false
    }
    return result
  },
  HandleReset() {
    var that = this
    that.setData({
      isHidden: true,
      username_value: that.getCurrentUsername(),
      specific_value: that.getSubmitTime(),
      nowText: '请选择',
      UploadImageURL:'',
    })
  },

  // 获取提交时间
  getSubmitTime() {
    var Time = ""
    var time = new Date()

    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()

    if(month>=10 && month<=12){
      month=month
    }else{
      month='0'+month
    }

    if(day>=10 && day<=12){
      day=day
    }else{
      day='0'+day
    }

    var hour = time.getHours()
    var minute = time.getMinutes()
    Time = year + "-" + month + "-" + day + " " + hour + ":" + minute
    return Time
  },
  // 从本地缓存获取用户名
  getCurrentUsername() {
    var username = ''
    username = wx.getStorageSync('userMessage').user
    return username
  },
  //点击上传图片按钮
  HandleUploadImage() {
    var that = this
    var fileID = ''
    common.uploadImage()
      .then(res => {  // res:返回上传图片的在后台ID
        fileID = res
        return res
      }).then(res => {
        // 通过图片ID获取图片真实地址
        common.getImageRealURL(fileID)
          .then(res => {
            that.setData({              
              upload_img:res
            })            
          })
      })

  },
  HandleInput(){
    var that=this
    that.setData({
      isHidden:true
    })
  }
})